<template>
  <div class="task-detail-view">
    <el-page-header @back="goToList">
      <template #content>
        <span class="text-large font-600 mr-3"> 任务详情 </span>
      </template>
    </el-page-header>

    <div v-if="taskLoading || flawLoading" v-loading="true" class="loading-state"></div>

    <div v-else-if="currentTask" class="main-container">
      <div class="content-area">
        <div class="image-area">
          <el-image
              v-if="selectedFlaw?.flawImageUrl"
              :src="selectedFlaw.flawImageUrl"
              fit="contain"
              :preview-src-list="[selectedFlaw.flawImageUrl]"
              hide-on-click-modal
          >
            <template #error>
              <div class="image-slot">图片加载失败</div>
            </template>
          </el-image>
          <div v-else class="image-slot">
            <el-icon><Picture /></el-icon>
            <span>请在右侧或下方时间轴上选择一个故障点以预览图片</span>
          </div>
        </div>
        <div class="scale-bar-area">
          <div class="scale-bar-wrapper">
            <div class="scale-bar-text start">0m</div>
            <div class="scale-bar-text end">{{ currentTask.taskTrip || 0 }}m</div>
            <div class="scale-bar">
              <div class="scale-bar-progress"></div>
            </div>
            <el-tooltip
                v-for="flaw in flaws"
                :key="flaw.id"
                :content="`${flaw.flawName} @ ${flaw.flawDistance}m`"
                placement="top"
            >
              <div
                  class="scale-bar-flaw"
                  :class="getFlawStatusClass(flaw)"
                  :style="{ left: calculateFlawPosition(flaw.flawDistance) }"
                  @click="handleSelectFlaw(flaw)"
              >
                <el-icon><Location /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>

      <div class="sidebar">
        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">任务信息</div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="任务编号">{{ currentTask.taskCode }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDateTime(currentTask.execTime) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDateTime(currentTask.endTime) }}</el-descriptions-item>
            <el-descriptions-item label="任务距离">{{ currentTask.taskTrip }} 米</el-descriptions-item>
            <el-descriptions-item label="故障总计">{{ faultCounts.total }}</el-descriptions-item>
            <el-descriptions-item label="已确认故障">
              <el-tag type="danger">{{ faultCounts.confirmed }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="疑似故障">
              <el-tag type="warning">{{ faultCounts.unconfirmed }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">故障历史</div>
          </template>
          <el-table :data="flaws" stripe style="width: 100%" height="300" @row-click="handleOpenFlawModal">
            <el-table-column prop="flawName" label="故障名称" />
            <el-table-column prop="flawType" label="故障类型" width="100" />
            <el-table-column prop="flawDistance" label="位置(m)" width="90" />
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="getFlawStatusTag(row)">{{ getFlawStatusText(row) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-empty v-else description="无法加载任务详情" />

    <AppModal v-model:visible="flawModalVisible" title="故障详情与确认" width="1000px">
      <div v-if="modalFlawData" class="modal-body">
        <div class="modal-image-container">
          <el-image :src="modalFlawData.flawImageUrl" fit="contain" />
        </div>
        <div class="modal-info-container">
          <el-form label-position="top">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="故障名称">{{ modalFlawData.flawName }}</el-descriptions-item>
              <el-descriptions-item label="故障类型">{{ modalFlawData.flawType }}</el-descriptions-item>
              <el-descriptions-item label="故障描述">{{ modalFlawData.flawDesc }}</el-descriptions-item>
              <el-descriptions-item label="故障位置">{{ modalFlawData.flawDistance }} 米</el-descriptions-item>
            </el-descriptions>
            <el-form-item label="是否属实" style="margin-top: 20px;">
              <el-radio-group v-model="modalFlawData.confirmed">
                <el-radio :value="true">是 (确认为故障)</el-radio>
                <el-radio :value="false">否 (非故障或误报)</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="补充说明">
              <el-input v-model="modalFlawData.remark" type="textarea" :rows="4" placeholder="请输入补充说明" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="flawModalVisible = false">取 消</el-button>
        <AppButton type="primary" :loading="isUpdatingFlaw" @click="handleConfirmFlaw">
          确 定
        </AppButton>
      </template>
    </AppModal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useTasksStore } from '@/stores/tasks';
import { listFlaw, updateFlaw } from '@/api/system'; // 直接调用API
import { storeToRefs } from 'pinia';
import { ElPageHeader, ElCard, ElTable, ElTableColumn, ElDescriptions, ElDescriptionsItem, ElTag, ElIcon, ElImage, ElTooltip, ElRadioGroup, ElRadio, ElForm, ElFormItem, ElInput, ElButton, ElEmpty, vLoading } from 'element-plus';
import { Picture, Location } from '@element-plus/icons-vue';
import { formatDateTime } from '@/utils';
import AppModal from '@/components/common/AppModal.vue';
import AppButton from '@/components/common/AppButton.vue';

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
});

const router = useRouter();
const tasksStore = useTasksStore();
const { currentTask, loading: taskLoading } = storeToRefs(tasksStore);

// --- Local State ---
const flaws = ref([]);
const flawLoading = ref(false);
const selectedFlaw = ref(null);
const flawModalVisible = ref(false);
const modalFlawData = ref(null);
const isUpdatingFlaw = ref(false);

// --- Computed Properties ---
const faultCounts = computed(() => {
  return flaws.value.reduce((acc, flaw) => {
    acc.total++;
    if (flaw.confirmed === true) acc.confirmed++;
    if (flaw.confirmed === null) acc.unconfirmed++;
    return acc;
  }, { total: 0, confirmed: 0, unconfirmed: 0 });
});

// --- Methods ---
// const goBack = () => {
//   router.back();
// };

const goToList = () =>{
  router.push("/tasks")
}

const fetchFlaws = async () => {
  flawLoading.value = true;
  try {
    const res = await listFlaw({ taskId: props.id, pageNum: 1, pageSize: 999 }); // 获取所有故障
    flaws.value = res.data.rows || [];
    // 默认选中第一个故障
    if (flaws.value.length > 0) {
      selectedFlaw.value = flaws.value[0];
    }
  } catch (error) {
    console.error("Failed to fetch flaws:", error);
  } finally {
    flawLoading.value = false;
  }
};

const handleSelectFlaw = (flaw) => {
  selectedFlaw.value = flaw;
};

const handleOpenFlawModal = (flaw) => {
  // 深拷贝一份数据到模态框，避免直接修改列表数据
  modalFlawData.value = JSON.parse(JSON.stringify(flaw));
  // 如果是null（疑似），默认选中“是”
  if (modalFlawData.value.confirmed === null) {
    modalFlawData.value.confirmed = true;
  }
  flawModalVisible.value = true;
};

const handleConfirmFlaw = async () => {
  if (!modalFlawData.value) return;
  isUpdatingFlaw.value = true;
  try {
    await updateFlaw(modalFlawData.value);
    flawModalVisible.value = false;
    // 成功后刷新故障列表
    await fetchFlaws();
  } catch(error) {
    console.error("Failed to update flaw:", error);
  } finally {
    isUpdatingFlaw.value = false;
  }
}

// --- Helper Functions for Template ---
const calculateFlawPosition = (distance) => {
  const totalDistance = currentTask.value?.taskTrip || 1; // 避免除以0
  const percentage = (distance / totalDistance) * 100;
  return `${Math.max(0, Math.min(percentage, 100))}%`;
};

const getFlawStatusClass = (flaw) => {
  if (flaw.confirmed === true) return 'confirmed';
  if (flaw.confirmed === false) return 'false-alarm';
  return 'unconfirmed'; // null
}
const getFlawStatusTag = (flaw) => {
  if (flaw.confirmed === true) return 'danger';
  if (flaw.confirmed === false) return 'info';
  return 'warning'; // null
}
const getFlawStatusText = (flaw) => {
  if (flaw.confirmed === true) return '已确认';
  if (flaw.confirmed === false) return '非故障';
  return '待确认'; // null
}

// --- Lifecycle ---
onMounted(async () => {
  await tasksStore.fetchTaskDetail(props.id);
  await fetchFlaws();
});
</script>

<style lang="scss" scoped>
@use '../assets/scss/variables' as *;

.task-detail-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: white;

  .el-page-header {
    padding: 16px 20px;
    border-bottom: 1px solid $border-color-light;
  }
}

.loading-state {
  flex: 1;
}

.main-container {
  flex: 1;
  display: flex;
  height: calc(100vh - 60px); // 减去头部高度
  overflow: hidden;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.image-area {
  flex: 1;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  .el-image {
    width: 100%;
    height: 100%;
  }
  .image-slot {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    font-size: $font-size-base;
    color: $text-color-secondary;
    .el-icon {
      font-size: 48px;
    }
  }
}

.scale-bar-area {
  height: 100px;
  background: $fill-color-light;
  border-top: 1px solid $border-color-light;
  padding: 20px;
  display: flex;
  align-items: center;
}

.scale-bar-wrapper {
  position: relative;
  width: 100%;
  height: 40px;
}
.scale-bar {
  width: 100%;
  height: 8px;
  background: #e4e7ed;
  border-radius: $border-radius-base;
  position: relative;
  margin: 16px 0;
}
.scale-bar-text {
  position: absolute;
  font-size: $font-size-small;
  color: $text-color-regular;
  top: -5px;
  &.start { left: 0; }
  &.end { right: 0; }
}
.scale-bar-flaw {
  position: absolute;
  top: 8px;
  width: 24px;
  height: 24px;
  border-radius: $border-radius-circle;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: $font-size-medium;
  color: white;
  cursor: pointer;
  transform: translateX(-50%);
  border: 2px solid white;
  transition: transform 0.2s ease;
  &:hover {
    transform: translateX(-50%) scale(1.2);
  }
  &.confirmed { background: $danger-color; }
  &.unconfirmed { background: $warning-color; }
  &.false-alarm { background: $info-color; }
}


.sidebar {
  width: $sidebar-width;
  border-left: 1px solid $border-color-light;
  display: flex;
  flex-direction: column;
  padding: 10px;
  gap: 10px;
  background: $bg-color;
  overflow-y: auto;
}

.info-card {
  border: none;
  :deep(.el-card__header) {
    background-color: $fill-color-light;
    font-weight: bold;
  }
}

.modal-body {
  display: flex;
  gap: 20px;
  height: 60vh;
}
.modal-image-container {
  flex: 3;
  background: #000;
  .el-image {
    width: 100%;
    height: 100%;
  }
}
.modal-info-container {
  flex: 2;
  overflow-y: auto;
}
</style>